package com.acmedcare.framework.exchange.center.executer.job;

import com.acmedcare.framework.exchange.center.core.handler.AgentHandlerMBean;
import com.acmedcare.framework.exchange.center.entity.bean.Task;
import com.acmedcare.framework.exchange.center.entity.bean.TaskDetail;
import com.acmedcare.framework.exchange.center.entity.dto.TaskFailStatus;
import com.acmedcare.framework.exchange.center.executer.ExecutorConfig;
import java.util.Date;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

@SuppressWarnings("unused")
@Slf4j
public class PluginJob extends BaseJob implements Job {

  @Override
  public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {

    //如果存在正在执行的任务，直接跳过执行
    AgentHandlerMBean agentHandler = (AgentHandlerMBean) ExecutorConfig.getInstance()
        .getApplicationContext().getBean("agentHandler");

    JobDetail detail = jobExecutionContext.getJobDetail();
    Task task = (Task) detail.getJobDataMap().get(ExecutorConfig.TASKINFO);
    task.setLastRunTime(new Date());
    publishTask(task);

    TaskDetail taskDetail = new TaskDetail();
    taskDetail.setExecutorName(ExecutorConfig.getInstance().getExecutorName());
    taskDetail.setName(task.getName());
    taskDetail.setDescription(task.getDescription());
    taskDetail.setExecuteTime(new Date());

    if (!task.getGroupName().equals(ExecutorConfig.getInstance().getGroupName())) {

      taskDetail.setDuringTime(Long.valueOf(0));
      taskDetail.setFailStatus(TaskFailStatus.SKIP);
      taskDetail.setExecuteLog(String.format("任务正在执行,或者当前环境与任务配置环境不匹配,当前环境为:%s,任务所处的环境为:%s"
          , ExecutorConfig.getInstance().getGroupName(), task.getGroupName()));
      taskDetail.setStatus(false);
      publishDetail(taskDetail);
      return;
    }

    long startTime = System.currentTimeMillis();   //获取开始时间
    StringBuilder stringBuilder = new StringBuilder();
    try {

      agentHandler.invoke(task);
      taskDetail.setStatus(true);

      } catch (Exception e) {

      stringBuilder.append(e.getMessage() + e.getStackTrace());
      taskDetail.setFailStatus(TaskFailStatus.ERROR);
      taskDetail.setStatus(false);
      throw new JobExecutionException("task convert fail", e);
      } finally {

      long endTime = System.currentTimeMillis(); //获取结束时间
      taskDetail.setDuringTime(endTime - startTime);
      taskDetail.setExecuteLog(stringBuilder.toString());
      publishDetail(taskDetail);
    }
  }
}
